{% extends 'IcsocUIBundle::page.html.twig' %}
{% from 'IcsocUIBundle:Macro:grid.html.twig' import gridWidth,gridNav,gridConfig %}
{% from 'IcsocUIBundle:Macro:actions.html.twig' import timebutton,searchtime,searchForm,searchFormBtn %}

{% block stylesheet %}
    {{ parent() }}
    {% stylesheets
    '@datepicker_css'
    '@jqgird_css'
    '@gritter_css'
    filter='cssrewrite' filter='uglifycss'
    %}
    <link rel="stylesheet" href="{{ asset_url }}" />
    {% endstylesheets %}
{% endblock %}

{% block content %}
    <h3 class="header smaller lighter green">下载任务管理:</h3>
    <p></p>
    <table class="table table-bordered table-hover no-padding">
        <tbody>
        <tr>
            <td class="col-xs-2 align-right align-middle" style="border-right-width: 0px;">
                <label for="start_time">开始时间:</label>
            </td>
            <td class="col-xs-4" style="border-left-width: 0px;">
                <div class="row" style="margin-right: 0">
                    <div class="col-sm-6">
                        <input type="text" class="col-sm-12" id="start_time" placeholder="" value="">
                    </div>
                </div>
            </td>
            <td class="col-xs-2 align-right align-middle" style="border-right-width: 0px;">
                <label for="end_time">结束时间:</label>
            </td>
            <td class="col-xs-4" style="border-left-width: 0px;">
                <div class="row" style="margin-right: 0">
                    <div class="col-sm-6">
                        <input type="text" class="col-sm-12" id="end_time" placeholder="" value="">
                    </div>
                </div>

            </td>
        </tr>
        <tr>
            <td colspan="4" class="text-center">
                <button id="loading-btn" onclick="search()" class="btn btn-info btn-sm">
                    <i class="ace-icon fa fa-search"></i> 查询
                </button>
                <button id="loading-btn"  class="btn btn-pink btn-sm" onclick="resetBtn()">
                    <i class="ace-icon fa fa-undo"></i> 重 置
                </button>
            </td>
        </tr>
        </tbody>
    </table>
    <table id="grid-table"></table>
    <div id="grid-pager"></div>
{% endblock %}

{% block footer %}
    {% javascripts
    '@datepicker_js'
    '@jqgird_js'
    '@gritter_js'
    '@common_js'
    filter='uglifyjs'
    %}
    <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
    <script type="text/javascript">
        var phone = '';
        var sendRes = '';
        var startTime = '';
        var endTime = '';
        var t1 = '';
        var allId = {};
        var tokenId = '';
        var newTokenId= '';
        $(function () {
            $('#start_time').datetimepicker({locale:'zh-cn',format:'YYYY-MM-DD HH:mm:ss',widgetPositioning:{horizontal:'left'}});
            $('#end_time').datetimepicker({locale:'zh-cn',format:'YYYY-MM-DD HH:mm:ss',widgetPositioning:{horizontal:'left'}});
        });
        jQuery(function($) {
            {{ gridWidth() }}
            getCondition();
            jQuery(grid_selector).jqGrid({
                caption: "下载任务列表",
                url: "{{ path('icsoc_security_develop_download_work_data') }}",
                mtype: 'POST',
                datatype: "json",
                hidegrid:false,
                height: '100%',
                colModel:[
                    {name:'name' , index:'name' , label: '任务名称' , width:250 , sortable:true , fixed:true},
                    {name : "progress_show", index:'progress_show', title : false, formatter : progressFormatter, label: '完成进度' , width:200, sortable:false},
                    {name:'datacount' , index:'datacount' , label: '总数据量(行)' , width:100 , sortable:true , fixed:true},
                    {name:'file_size' , index:'file_size' , label: '文件大小(KB)' , width:100 , sortable:true , fixed:true},
                    {name:'use_time' , index:'use_time' , label: '生成用时(s)' , width:100 , sortable:true , fixed:true},
                    {name : "id", index:'id', title : false, formatter : actFormatter, label: '操作' , width:100, sortable:false},
                    {name:'submit_time' , index:'submit_time', formatter:'date', formatoptions:{srcformat: 'U', newformat:'Y-m-d H:i:s'}, label: '提交时间' , width:80 , sortable:false },
                    {name:'id' , index:'id' , hidden : true },
                    {name:'progress' , index:'progress' , hidden : true },
                    {name:'download_url' , index:'download_url' , hidden : true },
                    {name:'token_id' , index:'token_id' , hidden : true },
                    {name:'export_version' , index:'export_version' , hidden : true }
                ],
                {{ gridConfig() }}
                rowNum:10,
                rowList: [10,20,30,50,100],
                rownumWidth: 40,
                viewrecords: true,
                sortname:"id",
                sortorder:'desc',
                multiselect: false,
                rownumbers: true,
                beforeRequest: function() {
                    window.clearInterval(t1);
                },
                gridComplete:function(data){
                    getData();
                    if(tokenId != '' || newTokenId != ''){
                        t1 = window.setInterval("newData()",5000);
                    }
                }
            });
            {{ gridNav(false,false,false,false) }}
            function actFormatter(cellvalue, options, rawObject) {
                var dis = '';
                if(rawObject.progress != 100){
                    dis = 'disabled="disabled';
                }
                var detail = '<button type="button" id="but'+rawObject.id+'" ' + dis + '" class="btn btn-white btn-pink btn-sm" onclick="showCustomDetail(\''
                        + rawObject.download_url +'\')">下载</button>';
                return "&nbsp;&nbsp;&nbsp;\t" + detail + "&nbsp;&nbsp;&nbsp;\t";
            }
            function progressFormatter(cellvalue, options, rawObject) {
                //进度条状态判断
                var now = '已生成' + rawObject.progress + '%';
                if(rawObject.progress == 100){
                    now = '完成，请下载！';
                }
                if(rawObject.progress == -100){
                    now = '失败的任务';
                }
                var detail = '<div class="progress pos-rel progress-striped" id="pro'+rawObject.id+'"  data-percent="'+now+'">'+
                                '<div class="progress-bar" style="width:'+rawObject.progress+'%;"></div>'+
                              '</div>';
                return detail;
            }
        });

        //搜索
        function search()
        {
            getCondition();
            $('#grid-table').setGridParam({
                page:1,
                postData:{'startTime':startTime, 'endTime':endTime}
            }).trigger("reloadGrid");
        }

        //重置
        function resetBtn()
        {
            startTime = $('#start_time').val('');
            endTime = $('#end_time').val('');
            search();
        }

        function getCondition()
        {
            startTime = $('#start_time').val();
            endTime = $('#end_time').val();
        }

        function newData(){
            getData();
            if(tokenId == '' && newTokenId == ''){
                window.clearInterval(t1);
                return;
            }
            $.ajax({
                type:'post',
                url:"{{ path('icsoc_security_download_upload_data') }}",
                datatype: "json",
                data:{
                    'allId':allId,
                    'tokenId':tokenId,
                    'newTokenId':newTokenId
                },
                success:function(e){
                    for(var key in e['data']){
                        var proid = '#pro'+key;
                        var prodata = '已生成'+e['data'][key]+'%';
                        var butid = '#but'+key;
                        if(e['data'][key] == 100){
                            prodata = '完成，请下载！';
                            $(butid).attr('onclick', "showCustomDetail('"+e['url'][key]+"')").attr('disabled', false);
                        }
                        var width = e['data'][key]+'%';
                        $(proid).attr('data-percent', prodata).children().css('width', width);
                        $("#grid-table").jqGrid('setCell', key, 'progress', e['data'][key]);
                        $("#grid-table").jqGrid('setCell', key, 'use_time', e['use_time'][key]);
                        $("#grid-table").jqGrid('setCell', key, 'datacount', e['datacount'][key]);
                        if(e['file_size'][key] > 0) {
                            $("#grid-table").jqGrid('setCell', key, 'file_size', e['file_size'][key]);
                        }
                    }
                    for(var key in e['msg_token_id']){
                        var proid = '#pro'+key;
                        $(proid).attr('data-percent', '失败的任务');
                        $("#grid-table").jqGrid('setCell', key, 'progress', '100'); //抑制再次请求
                        $("#grid-table").jqGrid('setCell', key, 'file_size', '0');
                    }
                }
            });
            //window.clearInterval(t1);
        }

        function getData(){
            tokenId = '';
            newTokenId = '';
            allId = {};
            var ids = $('#grid-table').getDataIDs();//返回数据表的ID数组["66","39"..]
            var len = ids.length;
            for(var i=0; i<len; i++){
                var getId = $('#grid-table').getRowData(ids[i]);//获取当前的数据行
                var rowData = $("#grid-table").jqGrid('getRowData',getId.id);
                var rowTokenId = rowData.token_id;
                var exportVersion = rowData.export_version;
                var rowProgress=rowData.progress;
                if (rowProgress != 100) {
                    if(exportVersion == 1){
                        tokenId += rowTokenId+',';
                    }else if(exportVersion == 2){
                        newTokenId += rowTokenId+',';
                    }

                    allId[getId.id] = rowTokenId;
                }
            }
            tokenId = tokenId.substring(0,tokenId.length-1);  //去除最后的逗号
            newTokenId = newTokenId.substring(0,newTokenId.length-1); //去除最后的逗号
        }

        function showCustomDetail(url){
            window.location.href=url;
        }
    </script>
{% endblock %}